import axios from 'axios'
import config from '@/config'
import store from '@/store'
import router from '@/router'

// const url = process.env.NODE_ENV === "production" ? config.baseURL.dev : config.baseURL.pro
const url = "http://127.0.0.1:8090"
const request = axios.create({
  timeout: 5000,
  baseURL: url
})

// axios.defaults.timeout = 5000
// axios.defaults.baseURL = url

request.interceptors.request.use(config => {
  const token = store.state.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, err => {
  console.log(err)
})

request.interceptors.response.use(response => {
  if (response.status === 200) {
    // 请求成功
    if (response.data.code == 200) {
      return Promise.resolve(response.data)
    }
    switch (response.data.code) {
      case 10001:
      case 10002:
      case 10003:
      case 10004:
      case 10005:
        router.replace({
          name: 'login',
        });
        // 清空token 等
        store.dispatch("setToken","")
        break;
      default:
        console.log(response.data)
    }
  } else {
    return Promise.reject(response)
  }
})

export default request